import { fileAddAPI, fileCheckChunkAPI} from '@/api/files';

// =========前端上传代码开始============
class MultiFileUploader {
    constructor(files, chunkSize = 10 * 1024 * 1024) {
        this.files = files;
        this.chunkSize = chunkSize;
    }

    async upload() {
        const allResults = [];
        
        // 为每个文件创建上传信息
        for (let fileIndex = 0; fileIndex < this.files.length; fileIndex++) {
            const file = this.files[fileIndex];
            const totalChunks = Math.ceil(file.size / this.chunkSize);
            const identifier = `${file.name}-${file.size}-${file.raw.lastModified}`;

            // 检查已上传的分片
            const uploadedChunks = await this.checkStatus(identifier);
            const uploadedSet = new Set(uploadedChunks);

            // 上传所有分片
            for (let chunkNumber = 1; chunkNumber <= totalChunks; chunkNumber++) {
                if (uploadedSet.has(chunkNumber)) continue;

                const start = (chunkNumber - 1) * this.chunkSize;
                const end = Math.min(start + this.chunkSize, file.size);
                const chunk = file.raw.slice(start, end);
                console.log('chunk',chunk)
                const formData = new FormData();
                formData.append('files', chunk);

                // 添加文件标识信息
                const fileIdentifiers = [{
                    chunkNumber,
                    totalChunks,
                    fileName: file.name,
                    identifier
                }];
                formData.append('fileIdentifiers', JSON.stringify(fileIdentifiers));
                
                const result = await fileAddAPI(formData);
                // const result = response.data.;

                if (result.data.completed && result.data.completed.length > 0) {
                    allResults.push(...result.data.completed);
                }
            }
        }

        return allResults;
    }

    async checkStatus(identifier) {
        const response = await fileCheckChunkAPI({
            identifier
        });
        return response.data.data;
    }
}

// 使用示例
async function uploadFiles(files, groupId) {
    const uploader = new MultiFileUploader(files, groupId);
    return await uploader.upload();
}

// =========前端上传代码结束============

export default MultiFileUploader